//
//  CZEmoticonTools.swift
//  weibo
//
//  Created by Apple on 16/3/20.
//  Copyright © 2016年 KY. All rights reserved.
//

import UIKit

//  每页显示多少行
let EmoticonRowOfPage = 3
//  每页显示多少列
let EmoticonColOfPage = 7
//  每页显示多少个表情
let EmoticonNumOfPage = EmoticonColOfPage * EmoticonRowOfPage - 1
//  相当于viewModel,处理emotion模型的逻辑
class CZEmoticonTools: NSObject {
    static let shareEmoticonTools = CZEmoticonTools()
    //  私有化构造函数
    private override init() {
        super.init()
    }
    //  获取图片的boundle路径
    private lazy var emotionBundle: NSBundle = {
        let boundlePath = NSBundle.mainBundle().pathForResource("Emoticons", ofType: "bundle")
        let bundle = NSBundle(path: boundlePath!)
        return bundle!
    }()
    
    //  最近表情数组
    private lazy var recentEmotions: [CZEmoticon] = {
        var localRecentEmotions = NSKeyedUnarchiver.unarchiveObjectWithFile(self.recentEmoticonPath) as? [CZEmoticon]
        if localRecentEmotions == nil {
            localRecentEmotions = [CZEmoticon]()
        } else {
            //  解决最近表情不显示，因为沙盒路径不对
            //  不等于nil，把前半段路径改成最新的获取的emotion.boundle路径，因为每次模拟的路径不一样
            for value in localRecentEmotions! {
                //  从后往前查找'/'获取范围
                let range = (value.path! as NSString).rangeOfString("/", options: NSStringCompareOptions.BackwardsSearch)
                //  获取图片的目录
                let imageDirectory = (value.path! as NSString).stringByReplacingCharactersInRange(NSMakeRange(0, range.location + 1), withString: "")
                //  根据图片文件夹生成图片路径
                let imagePath = self.emotionBundle.pathForResource(imageDirectory, ofType: nil)
                //  修改图片前半段路径
                value.path = imagePath
            }
        }
        return localRecentEmotions!
    }()
    
    //  default 默认表情数据
    private lazy var defaultEmotions: [CZEmoticon] = {
        return self.emotions("default/info.plist")
    }()
    //  emoji 数组
    private lazy var emojiEmotions: [CZEmoticon] = {
        return self.emotions("emoji/info.plist")
    }()
    //  浪小花数组
    private lazy var lxhEmotions: [CZEmoticon] = {
        return self.emotions("lxh/info.plist")
    }()
    
    lazy var allEmotions: [[[CZEmoticon]]] = {
        
        return [
            self.sectionWithEmotions(self.recentEmotions),
            self.sectionWithEmotions(self.defaultEmotions),
            self.sectionWithEmotions(self.emojiEmotions),
            self.sectionWithEmotions(self.lxhEmotions)
        ]
    }()
    //  最近使用表情路径
    private lazy var recentEmoticonPath: String = {
        let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("recentEmotions.archive")
        return path
    }()
    //  保存数据移除最后一个元素
    func saveRecentEmoticon(emoticon: CZEmoticon) {
        
        //  不能这样干，不能循环的时候改变数组，可以记录下来要删除的数据然后在循环完以后删除
        //  判断这个对象是否在这个最近表情数组里面，如果在移除掉
//        for (index, value) in recentEmotions.enumerate() {
//            //  类型一样说明有可能一样，类型不一样则一定不会重复
//            if value.isEmoji == emoticon.isEmoji {
//                //  如果是emoji表情，则比较code是否一样
//                if value.isEmoji {
//                    if value.code! == emoticon.code! {
//                        recentEmotions.removeAtIndex(index)
//                    }
//                } else {
//                    if value.chs! == emoticon.chs! {
//                        recentEmotions.removeAtIndex(index)
//                    }
//                }
//                
//            }
//        }
        
        //  解决方案
        let recentArray = recentEmotions as NSArray
        //  查找模型对应的index,按照顺序会查找
        let index = recentArray.indexOfObject(emoticon)
        //  数组已经存在的index
        if index != NSNotFound {
            recentEmotions.removeAtIndex(index)
        }
        
        
        recentEmotions.insert(emoticon, atIndex: 0)
        //  如果超过20个数组元素，则需要移除最后一个元素
//        while recentEmotions.count > 20 {
//            //  移除最后一个元素
//            recentEmotions.removeLast()
//        }
        if recentEmotions.count > 20 {
            recentEmotions.removeLast()
        }
        //  通过allEmotions拿到最近使用表情的数组，更新数据
        allEmotions[0][0] = recentEmotions
        //  归档数据
        NSKeyedArchiver.archiveRootObject(recentEmotions, toFile: recentEmoticonPath)
    }
    
    //  每组表情显示多少页
    private func sectionWithEmotions(emotions: [CZEmoticon]) -> [[CZEmoticon]] {
        //  计算出来总共多少页
        let pageCount = (emotions.count - 1) / EmoticonNumOfPage + 1
        var tempArray = [[CZEmoticon]]()
        for i in 0..<pageCount {
            
            let location = i * EmoticonNumOfPage
            var length = EmoticonNumOfPage
            //  如果开始位置+截取长度 大于 数组数量则说明数组越界
            if location + length > emotions.count {
                //  调整截取长度 = 数组数量 - 开始开始
                length = emotions.count - location
            }
            let rang = NSMakeRange(location, length)
            
            let subArray = (emotions as NSArray).subarrayWithRange(rang) as! [CZEmoticon]
            tempArray.append(subArray)
        }
        return tempArray
    }
    
    //  抽取通用的获取图片数组
    private func emotions(path: String) -> [CZEmoticon] {
        let defaultEmotionPath = self.emotionBundle.pathForResource(path, ofType: nil)
        let defaultEmotionArray = NSArray(contentsOfFile: defaultEmotionPath!)!
        var tempArray = [CZEmoticon]()
        for value in defaultEmotionArray {
            let emoticon = CZEmoticon(dic: value as! [String: AnyObject])
            emoticon.path = (defaultEmotionPath! as NSString).stringByDeletingLastPathComponent
            tempArray.append(emoticon)
        }
        return tempArray
    }
    
    //  根据表情字符串查找表情模型
    func emoticonWithEmoticonStr(emoticonStr: String?) -> CZEmoticon? {
    
        if emoticonStr == nil {
            return nil
        }
        
        //  通过循环查找,默认表情和lxh
//        for emoticon in defaultEmotions {
//            if emoticon.chs == emoticonStr {
//                return emoticon
//            }
//        }
//        
//        for emoticon in lxhEmotions {
//            if emoticon.chs == emoticonStr {
//                return emoticon
//            }
//        }
        
        //  通过数组过滤查找
        //  闭包的简单写法
        if let emoticon = defaultEmotions.filter({$0.chs == emoticonStr}).first {
            return emoticon
        }
        if let emoticon = lxhEmotions.filter({$0.chs == emoticonStr}).first {
            return emoticon
        }
        return nil
    }
    
}
